import json
from fastapi import APIRouter, Query
from datetime import datetime
from process import baseFunction
from controller import CdailyData, CLineData, CstockHq, CronbLog
from typing import Optional

router = APIRouter()


def get_current_time():
    return datetime.now(), datetime.now().date()


@router.get("/get_closeDate/")
async def get_close_date():
    now, today = get_current_time()
    close_date = baseFunction.find_last_trading_day(today, now)
    # print(close_date)
    return {"closeDate": close_date}


@router.get("/get_closeData/")
async def get_close_data(tradeDate: str, ts_code: str):
    result = CdailyData.getDailyData(tradeDate, ts_code)
    # print(result)
    return result


@router.get("/getLine_dailyData/")
async def read_Line_dailyData(
    tableName: str,
    period: str,
    columns: str,
    conditions: Optional[str] = None  # 接受 JSON 字符串
):
    # 如果 conditions 非空，则反序列化为字典
    if conditions:
        conditions = json.loads(conditions)

    result = CLineData.Line_daily_data(period, tableName, columns, conditions)
    return result


@router.get("/get_stocksHq_closed/")
async def read_stocksHq_closed(ts_codes: str = Query(...)):
    result = CstockHq.getStocksHq_closed(ts_codes)
    return result


@router.get("/get_stockList_min/")
async def read_stockList_min(tsCodeList: str = Query(...), tradeDate: str = Query(...)):
    """
    获取指定日期的股票分时数据
    :param tsCodeList: 股票代码列表，以逗号分隔
    :param tradeDate: 交易日期，格式为 'YYYYMMDD'
    :return: 股票分时数据
    """
    result = CstockHq.Cget_stocks_minute(tsCodeList, tradeDate)
    return result


@router.get("/get_cronb_closed_log/")
async def read_cronb_closed_log():
    result = CronbLog.get_cronb_closed_log()
    return result
